<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/21 0021
 * Time: 11:13
 */

namespace app\admin\controller;


use app\admin\model\Servicebuyorder;
use app\admin\service\Refund;
use app\common\BaseHelper;
use controller\BasicAdmin;
use think\Loader;

class TenantWxPay extends BasicAdmin
{
    private $appid = "";
    private $mch_id = "";
    private $device_info = "";
    private $body = "";
    /**
     * @return string
     * 获取随机字符串
     */
    public function getNonceStr(){
        $refundService = new Refund();
       return  strtoupper($refundService->getRandom());
    }

    /**
     * 微信支付config
     */
    public function wxConfig()
    {
        $wxPayConfig = new \WxPayConfig();
        $this->appid = $wxPayConfig['appid'];
        $this->mch_id = $wxPayConfig['mch_id'];
        $this->device_info = $wxPayConfig['device_info'];
        $this->body = $wxPayConfig['body'];
    }

    /**
     * @return mixed
     * 存储商户充值数据，生成订单
     */
    public function insterServicebuyorderParam(){
       $servicebyorderModel = new Servicebuyorder();
       $param['type'] = input('serviceType');//服务类型
       $param['payMethod'] = input("payMethod",0);
       $param['status'] =$servicebyorderModel::STATUS_0;//初始为新建
       $param["total"] = input("total");//充值总金额

       $param['orderNo'] = \app\api\service\Order::makeOrderNo();
       $param['createDate'] = date("Y-m-d h:i:s",time());
       $param['createOper'] = session("TENANT_ID");
       $param['tenantId'] = session("TENANT_ID");
       $productId = get_uniqid_id();
       $param['productId'] = $productId;
       $param['id'] = BaseHelper::getUUID();
       //保存商户充值订单
       $result = $servicebyorderModel->insertServicebuyorder($param);
       if($result){
           $data['code'] = $servicebyorderModel::STATUS_VALID;
           $data['orderNo'] = $param['orderNo'];
           $data['payMethod'] = $param['payMethod'];
           $data['total'] = $param['total'];
           $data['type'] = $param['type'];
           $data['productId'] = $param['productId'];
       }else{
            $data['code'] = $servicebyorderModel::STATUS_INVALID;
            $data['msg'] = "订单生成失败！";
       }
       return $data;
    }

    //调取微信统一下单接口
    private function TransferWxPayApi($result){
        Loader::import('example.WxPay',EXTEND_PATH,'.NativePay.php');
        //商户随机订单编号
        $notify = new \NativePay();
        /**
         * 流程：
         * 1、调用统一下单，取得code_url，生成二维码
         * 2、用户扫描二维码，进行支付
         * 3、支付完成之后，微信服务器会通知支付成功
         * 4、在支付成功通知中需要查单确认是否真正支付成功（见：notify.php）
         */

        $input = new \WxPayUnifiedOrder();
        if($result['type'] == 2){
            $body = '秒到充值中心-商户达达运费充值';
        }else{
            $body = '秒到充值中心-商户平台消费充值';
        }
        $input->SetBody($body);
        $input->SetAttach("秒到充值");
        $input->SetOut_trade_no($result['orderNo']);
        $input->SetTotal_fee($result['total']*100);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 60*60*24));
        $input->SetNotify_url(config('miniprogram.domain')."/api/WxNotify/index");
        $input->SetTrade_type("NATIVE");
        $input->SetProduct_id($result['productId']);
        $result = $notify->GetPayUrl($input);
        $url = $result["code_url"];
        $payurl = $this->getPayImgUrl($url);
        return $payurl;
    }

    //把微信的code_url生成二维码
    private function getPayImgUrl($url = '',$size = 5){
        Loader::import('WxPay.phpqrcode',EXTEND_PATH,'.php');
        $level = 'L';// 纠错级别：L、M、Q、H
        //生成二维码图片
        ob_start();
        $QR = new \QRcode();
        $QR->png($url,false,$level,$size,2);
        $imageString = base64_encode(ob_get_contents());
        ob_end_clean();
        return "data:image/jpg;base64,".$imageString;

    }

    /**
     * @param $result
     */
    private function judgeRechargeType($result){

        $servicebuyorderModel = new Servicebuyorder();
        if($result['payMethod'] == $servicebuyorderModel::PAY_METHOD_WX){
            //调取微信扫码支付
          $WxResult = $this->TransferWxPayApi($result);

          return $WxResult;
        }else if($result['payMethod'] = $servicebuyorderModel::PAY_METHOD_ZHIFUBAO){
            //调取调取支付宝扫码支付




        }else{
            //调取网银支付



        }
    }

    //商户充值
    public function tenantRecharge(){
        //生成物流充值订单充值订单
        $result = $this->insterServicebuyorderParam();
        if($result['code']){

            //判断充值平台类型，调取对应充值平台
            $url = $this->judgeRechargeType($result);

            $param["url"] = $url;
            $param["code"] = config("status.SUCCESS_STATUS");
           return show(config("status.SUCCESS_STATUS"),"获取支付成功",$param);
        }else{
            $param["code"] = config("status.ERROR_STATUS");
            return show(config("status.ERROR_STATUS"),"获取支付成功",$param);
        }
    }



}